<?php

namespace app\admin\controller\file;

use app\admin\library\RedisHash;
use app\common\controller\Backend;
use think\Db;
use think\Env;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 物品管理
 *
 * @icon fa fa-circle-o
 */
class Item extends Backend
{

    /**
     * CommonItem模型对象
     * @var \app\admin\model\file\Item
     */
    protected $model = null;
    protected $redisHash = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\file\Item;
        $options = [
            'host' => Env::get('redis.host'),
            'port' => 6379,
            'password' => Env::get('redis.pass'),
            'select' => 0,
            'timeout' => 0,
            'persistent' => false,
        ];
        $this->redisHash = new RedisHash($options);
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {
        set_time_limit(0);
        $items = file_get_contents(ROOT_PATH."/public/template/CommonItem.txt");
        $header = [
            'id','class','quality','type','medindex','icon','name','desc',
            'level','price','sale_price','rule','num','script_id','skill_id',
            'is_cost','need_skill','need_skill_level','own_num','obj_type',
            'type_desc','quality_level','recipe_id','color','subclass','is_boardcast'
        ];
        $data = [];/*总数据*/
        $ids = [];/*所有列表的索引*/
        $idNames = [];/*[id=>1,name=>equipName]*/
        $item = explode("\n",$items);
        $result = true;
        foreach($item as $value){
            $cols=explode("\t",mb_convert_encoding(trim($value),'UTF-8','gb18030'));//按竖线进行拆分
            //过滤空行
            if($value=="")continue;

            //过滤一些没有内容的行，表头，然后一些注释行。
            if (
                in_array('',$cols) ||
                in_array('INT',$cols) ||
                in_array('int',$cols) ||
                in_array('index',$cols) ||
                in_array('INDEX',$cols) ||
                in_array('Index',$cols)
            ) {
                continue;
            }
            //过滤表头有#号注释行的
            if (strpos($cols[0],'#') === 0 ) {
                continue;
            }

            //判断有没有数据字段不匹配的，比如表头26个字段，内容也必须是这个字段，不然不可能成功
            if (count($header) != count($cols)) {
                continue;
            }
            $allData = array_combine($header,$cols);
            $newCols = [$cols[0]=>json_encode($allData)];
            array_unshift($data,$newCols);
            array_unshift($ids,$allData['id']);
            array_unshift($idNames,['id'=>$allData['id'],'name'=>$allData['name']]);
            $this->redisHash->hmset('item',$newCols);
        }
        $this->redisHash->hmset('item_ids',$ids);
        $this->redisHash->hmset('item_id_name',$idNames);
        if ($result) {
            return "数据同步成功";
        } else {
            return "数据同步失败";
        }
    }

    /**
     * 详情
     */
    public function detail($ids = null)
    {
        $row = $this->redisHash->hget('item',$ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign("row", json_decode($row,true));
        return $this->view->fetch();
    }

}
